﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using JDKill.Definitions.Product;
using JDKill.UIs.Common;
using System.Diagnostics;
using JDKill.Definitions.Address;
using TDLib.Utils;

namespace JDKill.UIs.Query
{
    public partial class PanelQueryProduct : UserControl
    {
        public PanelQueryProduct()
        {
            InitializeComponent();
        }

        public event EventHandler<AddToProductKillListEventArgs> AddToProductKillList;

        void QueryProductsPanel_Load(object sender, EventArgs e)
        {
            // 填充监控页面中的种类
            foreach (var category in ProductCategory.AllCategory)
            {
                int index = this.panelSeries.Controls.Count - 1;
                CheckBox checkBoxLast = this.panelSeries.Controls[index] as CheckBox;
                CheckBox checkBoxNew = new CheckBox();
                checkBoxNew.Anchor = AnchorStyles.Left | AnchorStyles.Top;
                checkBoxNew.Text = category.Name;
                checkBoxNew.AutoSize = true;
                checkBoxNew.Tag = category;
                checkBoxNew.Font = new Font("宋体", 9);
                checkBoxNew.Top = checkBoxLast.Top;
                checkBoxNew.Left = checkBoxLast.Right + 2;
                this.panelSeries.Controls.Add(checkBoxNew);
            }
            (this.panelSeries.Controls[0] as CheckBox).Checked = false;

            // 查询所有省份
            var areaList = GlobalContext.KillService.QuerySubAreaListOfChina();
            // 填充省数据
            FillComboBox(this.comboBox1, "请选择省", areaList);
            var locationId = ConfigStorage.ReadLocationId();
            var locationName = ConfigStorage.ReadLocationName();
            if (locationId != null && locationName != null)
            {
                var ids = locationId.Split('_');
                var names = locationName.Split('_');
                // 选择省
                int index1 = areaList.FindIndex(m => m.id == ids[0]);
                if (index1 != -1)
                {
                    this.comboBox1.SelectedIndex = index1 + 1;
                }
                // 选择市
                this.comboBox2.Items.Add("请选择市");
                this.comboBox2.Items.Add(new AreaInfo(){id = ids[1],name = names[1]});
                this.comboBox2.SelectedIndex = 1;
                // 选择县
                this.comboBox3.Items.Add("请选择县");
                this.comboBox3.Items.Add(new AreaInfo() { id = ids[2], name = names[2] });
                this.comboBox3.SelectedIndex = 1;
            }
            else
            {
                // 选择市
                this.comboBox2.Items.Add("请选择市");
                this.comboBox2.SelectedIndex = 0;

                // 选择县
                this.comboBox3.Items.Add("请选择县");
                this.comboBox3.SelectedIndex = 0;
            }
            // 绑定省变化事件
            this.comboBox1.SelectedIndexChanged += (o, args) => {
                var areaInfo = this.comboBox1.SelectedItem as AreaInfo;
                List<AreaInfo> list = null;
                if (areaInfo != null)
                {
                    list = GlobalContext.KillService.QuerySubAreaList(areaInfo.id);
                }
                FillComboBox(this.comboBox2, "请选择市", list);
            };
            // 绑定市变化事件
            this.comboBox2.SelectedIndexChanged += (o, args) =>
            {
                var areaInfo = this.comboBox2.SelectedItem as AreaInfo;
                List<AreaInfo> list = null;
                if (areaInfo != null)
                {
                    list = GlobalContext.KillService.QuerySubAreaList(areaInfo.id);
                }
                FillComboBox(this.comboBox3, "请选择县", list);
            };
        }

        private void FillComboBox(ComboBox comboBox, string defaultValue, List<AreaInfo> areaList)
        {
            comboBox.Items.Clear();
            comboBox.Items.Add(defaultValue);
            if (areaList!=null)
            {
                foreach (var item in areaList)
                {
                    comboBox.Items.Add(item);
                } 
            }
            comboBox.SelectedIndex = 0;
        }

        private void checkBoxSeriesAll_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < panelSeries.Controls.Count; i++)
            {
                CheckBox cb = panelSeries.Controls[i] as CheckBox;
                cb.Checked = checkBoxSeriesAll.Checked;
            }
        }

        public List<ProductCategory> GetQueryCategoryList()
        {
            List<ProductCategory> categoryList = new List<ProductCategory>();
            for (int i = 0; i < this.panelSeries.Controls.Count; i++)
            {
                CheckBox cb = this.panelSeries.Controls[i] as CheckBox;
                if (cb.Checked && cb.Tag != null)
                {
                    categoryList.Add(cb.Tag as ProductCategory);
                }
            }

            return categoryList;
        }

        public void ClearProductList()
        {
            this.listViewProductList.Items.Clear();
        }

        public int GetProductRowCount()
        {
            return this.listViewProductList.Items.Count;
        }

        public string GetLocationId()
        {
            var a1 = this.comboBox1.SelectedItem as AreaInfo;
            var a2 = this.comboBox2.SelectedItem as AreaInfo;
            var a3 = this.comboBox3.SelectedItem as AreaInfo;
            if (a1 != null && a2 != null && a3 != null)
            {
                return string.Format("{0}_{1}_{2}", a1.id, a2.id, a3.id);
            }
            return null;
        }

        public string GetLocationName()
        {
            var a1 = this.comboBox1.SelectedItem as AreaInfo;
            var a2 = this.comboBox2.SelectedItem as AreaInfo;
            var a3 = this.comboBox3.SelectedItem as AreaInfo;
            if (a1 != null && a2 != null && a3 != null)
            {
                return string.Format("{0}_{1}_{2}", a1.name, a2.name, a3.name);
            }
            return null;
        }

        public void RenderProductList(Dictionary<ProductCategory, List<ProductDetail>> productDic)
        {
            int index = 0;
            foreach (var item in productDic)
            {
                var category = item.Key;
                foreach (var product in item.Value)
                {
                    ListViewItem lv = new ListViewItem(new string[]
                    {
                        (++index).ToString(),
                        category.ToString(),
                        product.Id,
                        product.Name,
                        product.Price.ToString(),
                        product.KillPrice == -1 ? "-" : product.KillPrice.ToString(),
                        product.SaleCount = product.SaleCount.ToString(),
                        product.LeftCount = product.LeftCount.ToString(),
                        product.IsBuyAvailable()?"1":"0"
                    });
                    if (product.IsBuyAvailable())
                    {
                        lv.BackColor = GlobalContext.OnSaleColor;
                    }
                    lv.Tag = product;
                    this.listViewProductList.Items.Add(lv);
                }
            }
        }

        private void listViewProductList_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                if (this.listViewProductList.SelectedItems.Count > 0)
                {
                    ContextMenuStrip cms = new ContextMenuStrip();
                    if (!GlobalContext.IsInProductKillProcess)
                    {
                        // 抢购的过程中不能再添加商品
                        cms.Items.Add("添加到抢购列表", null, (o, args) =>
                        {
                            var selectedItems = this.listViewProductList.SelectedItems;
                            for (int i = 0; i < selectedItems.Count; i++)
                            {
                                var selectedItem = selectedItems[i];
                                var product = selectedItem.Tag as ProductDetail;
                                if (this.AddToProductKillList != null)
                                {
                                    AddToProductKillListEventArgs args0 = new AddToProductKillListEventArgs();
                                    args0.Product = product;
                                    this.AddToProductKillList(this, args0);
                                }
                            }
                        });
                    }
                    cms.Items.Add("查看商品图片", null, (o, args) =>
                    {
                        var selectedItems = this.listViewProductList.SelectedItems;
                        var selectedItem = selectedItems[0];
                        var product = selectedItem.Tag as ProductDetail;
                        if (product.Images == null || product.Images.Count < 1)
                        {
                            product.Images = GlobalContext.KillService.QueryProductImages(product.Id);
                        }
                        if (product.Images.Count > 0)
                        {
                            string imgUrl = product.Images[0];
                            Image img = GlobalContext.KillService.GetImage(imgUrl);
                            var frm = new FrmViewPic(img);
                            frm.ShowDialog();
                        }
                    });
                    cms.Items.Add("查看商品详情", null, (o, rags) =>
                    {
                        var selectedItems = this.listViewProductList.SelectedItems;
                        var selectedItem = selectedItems[0];
                        var product = selectedItem.Tag as ProductDetail;
                        var url = GlobalContext.KillService.GetProductDetailUrl(product.Id);
                        Process.Start(url);
                    });
                    cms.Items.Add("预约商品", null, (o, args) =>
                    {
                        var selectedItems = this.listViewProductList.SelectedItems;
                        var selectedItem = selectedItems[0];
                        var product = selectedItem.Tag as ProductDetail;
                        try
                        {
                            GlobalContext.KillService.ReserveProduct(product);
                            MsgBox.Info("预约成功！");
                        }
                        catch (Exception ex)
                        {
                            MsgBox.Warning(ex.Message);
                        }
                    });
                    cms.Show(this.listViewProductList, e.Location);
                }
            }
        }

        private void toolStripButtonAddCustom_Click(object sender, EventArgs e)
        {
            var frm = new FrmAddCustomProduct();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                string productId = frm.ProductId;
                if (!GlobalContext.CustomProducts.Contains(productId))
                {
                    GlobalContext.CustomProducts.Add(productId);
                    ConfigStorage.SaveCustomProducts(GlobalContext.CustomProducts);
                    GlobalContext.DoOutput("已经将商品" + productId + "添加到自定义组!");
                }
            }
        }
    }
}
